package com.example.demo.controller;

import com.example.demo.entity.Menu;
import com.example.demo.service.IMenuService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/admin")
public class MenuController {

    @Autowired
    private IMenuService menuService;

    @RequestMapping("/menuList")
    public String list(Model model,@RequestParam(value="pageNum",defaultValue="1")Integer pageNum) {
        PageHelper.startPage(pageNum, 5);
        List<Menu> menuList = menuService.selectAll();
        PageInfo pageInfo=new PageInfo(menuList);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("menuList", menuList);

        return "admin/menu/menuList";
    }


    @RequestMapping("/toEditMenu")
    public String toedit(Model model, Integer id) {

        List<Menu> menuDtos = menuService.getMenu();
        model.addAttribute("menuDtos", menuDtos);

        if (id != null) {
            Menu menu = menuService.selectById(id);
            model.addAttribute("menu", menu);
        }

        return "admin/menu/edit";
    }

    @RequestMapping("/editMenu")
    public String edit(Menu menu) {

        if (menu.getId() != null ) {
            menuService.update(menu);
        } else {
            menuService.insert(menu);
        }

        return "redirect:menuList";
    }

    @RequestMapping("/deleteMenu")
    public String delete(Integer id) {

        menuService.delete(id);
        return "redirect:menuList";
    }

}
